package com.compass.doctor.ui.home.fragment

import android.os.Bundle
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.compass.doctor.R
import com.compass.doctor.base.BaseVBFragment
import com.compass.doctor.callback.OnCustomButtonClick
import com.compass.doctor.callback.OnRefusalButtonClick
import com.compass.doctor.databinding.FragmentNewHomeBinding
import com.compass.doctor.dialog.ChoosePhoneDialog
import com.compass.doctor.ui.MainViewModel
import com.compass.doctor.ui.WebDetailActivity
import com.compass.doctor.ui.consultation.ConsultationCenterActivity
import com.compass.doctor.ui.home.FollowUpActivity
import com.compass.doctor.ui.home.KnowledgeCenterActivity
import com.compass.doctor.ui.home.TeamDoctorActivity
import com.compass.doctor.ui.home.VAServiceActivity
import com.compass.doctor.ui.home.adapter.InquiryOrderAdapter
import com.compass.doctor.ui.home.adapter.MenuAdapter
import com.compass.doctor.ui.home.view.InquiryInfoView
import com.compass.doctor.ui.home.viewmodel.InquiryOrderViewModel
import com.compass.doctor.ui.message.NotificationActivity
import com.compass.doctor.ui.mine.EditUserDataActivity
import com.compass.doctor.ui.mine.view.DoctorInfoView
import com.compass.doctor.ui.patient.PatientChatActivity
import com.compass.doctor.ui.patient.PractitionerToPatientChatActivity
import com.compass.doctor.ui.patient.VideoCallActivity
import com.compass.doctor.ui.patient.viewmodel.VideoCallViewModel
import com.compass.doctor.ui.prescription.PrescriptionTypeActivity
import com.compass.framework.constant.CLINICAL_RECEPTION
import com.compass.framework.constant.REFRESH_LAUNCH
import com.compass.framework.constant.REFRESH_MESSAGE
import com.compass.framework.constant.REFRESH_RX
import com.compass.framework.constant.REFRESH_RX_EXAMINE
import com.compass.framework.constant.REFUSE_RECEPTION
import com.compass.framework.constant.TOOLS_URl
import com.compass.framework.decoration.NormalItemDecoration
import com.compass.framework.dialog.CommonMessageDialog
import com.compass.framework.ext.gone
import com.compass.framework.ext.load
import com.compass.framework.ext.onClick
import com.compass.framework.ext.toJson
import com.compass.framework.ext.visible
import com.compass.framework.manager.DictionariesManager
import com.compass.framework.manager.UserInfoManager
import com.compass.framework.model.MenuItem
import com.compass.framework.toast.TipsToast
import com.compass.framework.utils.LiveDataBus
import com.compass.framework.utils.dpToPx
import com.compass.framework.utils.getStringFromResource
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.netease.yunxin.kit.corekit.im.model.UserInfo
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener
import com.scwang.smart.refresh.layout.listener.OnRefreshListener
import kotlin.properties.Delegates

/**
 * Description： 新首页
 * Date:2024/10/23 10:51
 */
class NewHomeFragment : BaseVBFragment<FragmentNewHomeBinding>(), OnRefreshListener,
    OnLoadMoreListener {
    private val videoCallViewModel: VideoCallViewModel by viewModels()
    private val mainViewModel: MainViewModel by activityViewModels()
    private var menuItems: ArrayList<MenuItem> = ArrayList()
    private lateinit var customDoctorInfoView: DoctorInfoView //医生信息view
    private lateinit var inquiryInfoView: InquiryInfoView
    private lateinit var mMenuAdapter: MenuAdapter//功能菜单adapter
    private val inquiryOrderViewModel: InquiryOrderViewModel by viewModels()
    private lateinit var mAdapter: InquiryOrderAdapter
    private var mPage = 1
    private var orderType: Int = 2//1-待接诊 2-已接诊 3-已完成 可不传所有
    private var onlineStatus: Int = 0
    override fun initView(view: View, savedInstanceState: Bundle?) {
        customDoctorInfoView = DoctorInfoView(requireContext(), 1)
        inquiryInfoView = InquiryInfoView(requireActivity())
        mMenuAdapter = MenuAdapter(1)

        when (UserInfoManager.getUserType()) {
            "1" -> {
                //医生
                initMenu()
                mBinding?.llMenu?.visible()
            }

            else -> {
                mBinding?.llMenu?.gone()
            }
        }


        mBinding?.apply {
            refreshLayout.setEnableRefresh(true)
            refreshLayout.setEnableLoadMore(true)
            refreshLayout.setOnRefreshListener(this@NewHomeFragment)
            refreshLayout.setOnLoadMoreListener(this@NewHomeFragment)
            flyContainer.addView(customDoctorInfoView)
            flyInquiryInfo.addView(inquiryInfoView)

            relNotification.onClick {
                //通知
                NotificationActivity.start(requireContext())
            }

            rcyMenu.apply {
                layoutManager =
                    LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
                adapter = mMenuAdapter
                indicator.setWithRecyclerView(rcyMenu, LinearLayoutManager.HORIZONTAL)
            }


            mMenuAdapter.onItemClickListener = { view: View, position: Int ->
                onMenuClick(menuItems[position].id)
            }

            mAdapter = InquiryOrderAdapter(orderType)
            val dp10 = dpToPx(10)
            recyclerView.apply {
                layoutManager = LinearLayoutManager(context)
                addItemDecoration(NormalItemDecoration().apply {
                    setBounds(left = dp10, top = dp10, right = dp10, bottom = dp10)
                    setLastBottom(true)
                })
                adapter = mAdapter
            }
            mAdapter.setBottomCallBack(onBottomClick)


        }
    }

    private fun setOnLineStatus(onlineStatus: Int) {
        this.onlineStatus = onlineStatus
        when (onlineStatus) {
            0 -> {
                mBinding?.tvOnLine?.text = "空闲"
                mBinding?.scOnLine?.isChecked = false
            }

            1 -> {
                mBinding?.tvOnLine?.text = "忙碌"
                mBinding?.scOnLine?.isChecked = true
            }
        }

    }

    override fun initData() {
        showLoading()
        mainViewModel.getAllDictionaries()
        mainViewModel.allDictionariesLiveData.observe(this) {
            //doctor_urgency_backlog_type
            it?.let {
                when (UserInfoManager.getUserType()) {
                    "1" -> {
                        mainViewModel.dictionariesLiveData.value =
                            it.doctor_urgency_backlog_doctor_type
                        DictionariesManager.saveDoctorUrgencyBacklogType(it.doctor_urgency_backlog_doctor_type.toJson())
                    }

                    "2" -> {
                        mainViewModel.dictionariesLiveData.value =
                            it.doctor_urgency_backlog_nurse_type
                        DictionariesManager.saveDoctorUrgencyBacklogType(it.doctor_urgency_backlog_nurse_type.toJson())
                    }

                    "3" -> {
                        mainViewModel.dictionariesLiveData.value =
                            it.doctor_urgency_backlog_pharmacist_type
                        DictionariesManager.saveDoctorUrgencyBacklogType(it.doctor_urgency_backlog_pharmacist_type.toJson())
                    }
                }

                //后期优化
                DictionariesManager.savePrescriptionFrequency(it.prescription_frequency.toJson())
                DictionariesManager.savePrescriptionChannel(it.prescription_channel.toJson())
                DictionariesManager.savePrescriptionUsage(it.prescription_usage.toJson())
                DictionariesManager.saveNurseProjectType(it.nurse_project_type.toJson())
                DictionariesManager.saveNurseStatus(it.app_order_nurse_status.toJson())
                DictionariesManager.saveConsultationStatus(it.medical_consultation_status.toJson())
                DictionariesManager.saveConsultationStatus(it.medical_consultation_status.toJson())
                DictionariesManager.saveParticipationStatus(it.medical_consultation_doctor_status.toJson())
                DictionariesManager.saveOrderStatus(it.order_prescription_status.toJson())
                DictionariesManager.saveOrderConsultationType(it.order_consultation_type.toJson())
                DictionariesManager.saveWalletLogType(it.doctor_wallet_log_type.toJson())
                DictionariesManager.saveWalletLogSource(it.doctor_wallet_log_source.toJson())
                DictionariesManager.saveOrderInspectionSource(it.order_inspection_status.toJson())
                DictionariesManager.saveNotificationType(it.doctor_notification_message_type.toJson())
                DictionariesManager.saveDoctorPosition(it.doctor_position.toJson())
                DictionariesManager.saveInspectionReportType(it.inspection_report_type.toJson())
                DictionariesManager.saveAfterStatus(it.order_nurse_after_sale_apply_status.toJson())
            }

        }
        mainViewModel.userLiveData.observe(this) {
            it?.let { doctorInfo ->
                mBinding?.tvHospitalName?.text = doctorInfo.getHospitalNameString()
                customDoctorInfoView.setDoctorInfo(doctorInfo)
//                LogUtil.d("医生信息：${doctorInfo.toJson()}")
                if (doctorInfo.name.isEmpty() || (doctorInfo.auditStatus == -1 || doctorInfo.auditStatus == 0)) {
                    EditUserDataActivity.start(
                        requireContext(),
                        doctorInfo.auditStatus,
                        doctorInfo.auditReason
                    )
                }
                setOnLineStatus(doctorInfo.onlineStatus)
            }


        }
        videoCallViewModel.onlineStatusLiveData.observe(this) {
            mainViewModel.getUserInfo()
        }


        mainViewModel.todayNumberLiveData.observe(this) {
            it?.let { todayNumber ->
                if (todayNumber.unreadMsgNum > 0) mBinding?.imgMessage?.visible() else mBinding?.imgMessage?.gone()
                inquiryInfoView.setInquiryInfo(todayNumber)


            }
        }

        inquiryOrderViewModel.orderLiveData.observe(this) {
            dismissLoading()
            if (mPage == 1) {
                mAdapter.setData(it)
                mBinding?.refreshLayout?.finishRefresh()
                mBinding?.refreshLayout?.setEnableLoadMore(load(it?.size))
                if (it.isNullOrEmpty()) {
                    mBinding?.emptyView?.visible()
                } else {
                    mBinding?.emptyView?.gone()
                }
            } else {
                mBinding?.refreshLayout?.finishLoadMore()
                if (!it.isNullOrEmpty()) {
                    mAdapter.addAll(it)
                } else {
                    mBinding?.refreshLayout?.setEnableLoadMore(false)
                }
            }
        }
        inquiryOrderViewModel.callLiveData.observe(this) {
            if (it) {
                showToast("正在为您呼叫患者，请稍后")
            }
        }
        inquiryOrderViewModel.finishLiveData.observe(this) {
            dismissLoading()
            if (it) {
                LiveDataBus.get().with(CLINICAL_RECEPTION).postValue(CLINICAL_RECEPTION)
                showToast("结束成功")
            }
        }

        //这里的通知后续根据通知消息后面再重新优化
        LiveDataBus.get().with(REFRESH_RX, String::class.java).observe(this) {
            //处方审核操作通知  护师操作刷新
            getHomeInfo()
        }

        //药师审核刷新
        LiveDataBus.get().with(REFRESH_RX_EXAMINE, String::class.java).observe(this) {
            //处方审核操作通知  护师操作刷新
            getHomeInfo()
        }

        LiveDataBus.get().with(REFRESH_LAUNCH, String::class.java).observe(this) {
            //会诊加入拒绝

        }


        LiveDataBus.get().with(REFRESH_MESSAGE, String::class.java)
            .observe(this) {
                getHomeInfo()
            }

        LiveDataBus.get().with(REFUSE_RECEPTION, String::class.java)
            .observe(this) {
                //拒诊 转诊
                getHomeInfo()
            }
        LiveDataBus.get().with(CLINICAL_RECEPTION, String::class.java)
            .observe(this) {
                // 接诊 结束
                getHomeInfo()
            }

        getHomeInfo()//获取紧急代办
    }

    private var consultationIsOpen: Boolean = true
    override fun intListener() {

        mBinding?.scOnLine?.onClick {

            when (onlineStatus) {
                0 -> {
                    videoCallViewModel.updateOnlineStatus("1")
                }

                1 -> {
                    videoCallViewModel.updateOnlineStatus("0")
                }
            }
            consultationIsOpen = !consultationIsOpen

            onlineStatus = if (consultationIsOpen) 1 else 0

        }


    }

    private fun initMenu() {
        menuItems.add(
            MenuItem(
                1,
                1,
                getStringFromResource(R.string.menu_medical_care),

                R.mipmap.icon_yh
            )
        )
        menuItems.add(
            MenuItem(
                1,
                2,
                getStringFromResource(R.string.chronic_disease_follow_up),
                R.mipmap.icon_chronic_disease_follow_up
            )
        )
        menuItems.add(
            MenuItem(
                1,
                3,
                getStringFromResource(R.string.knowledge_center),
                R.mipmap.icon_knowledge_center
            )
        )
        menuItems.add(
            MenuItem(
                1,
                4,
                getStringFromResource(R.string.consultation_center),
                R.mipmap.icon_added_service
            )
        )
        menuItems.add(
            MenuItem(
                1,
                5,
                getStringFromResource(R.string.menu_common_tools),
                R.mipmap.icon_team_doctors
            )
        )
        menuItems.add(
            MenuItem(
                1,
                6,
                getStringFromResource(R.string.menu_team_doctors),
                R.mipmap.icon_common_tools
            )
        )
        mMenuAdapter.setData(menuItems)

    }


    private var onRefusalBottomClick = object : OnRefusalButtonClick {
        override fun onButtonCallBack(orderId: String, msg: String) {
            showLoading()
            inquiryOrderViewModel.clinicalReception(orderId, 2, msg)

        }

    }

    private var onBottomClick = object : OnCustomButtonClick {
        override fun onButtonCallBack(position: Int, msgType: String?) {
            val item = mAdapter.getItem(position)
            item?.let { order ->
                when (msgType) {

                    "callPatient" -> {


                        callPhone(
                            order.id,
                            UserInfoManager.getUserInfo()?.mobile,
                            UserInfoManager.getUserInfo()?.alternativeMobile
                        )
                    }

                    "details" -> {

                        goToChat(
                            UserInfo(
                                order.patientWyyxAccid,
                                order.patientName,
                                order.patientAvatar
                            ), order.patientId
                        )


//                        ChatUtils.startVideoCall(context, "1709603162725")
                    }

                    "video" -> {
                        //这里改为处方 不呼叫了
                        PrescriptionTypeActivity.start(
                            requireContext(), UserInfo(
                                order.patientWyyxAccid,
                                order.patientName,
                                order.patientAvatar
                            ),
                            order.patientId,
                            ""
                        )

//                        VideoCallActivity.start(requireContext(),order.patientWyyxAccid,order.id)
//                        ChatUtils.startVideoCall(context, order.patientWyyxAccid)
                    }

                    "records" -> {

                        goToChat(
                            UserInfo(
                                order.patientWyyxAccid,
                                order.patientName,
                                order.patientAvatar
                            ), order.patientId
                        )


                    }

                    "checkout" -> {
                        //结束问诊
                        showLoading()
                        inquiryOrderViewModel.finishInterrogation(order.id, null)


//                        FinishInquiryDialog.Builder(
//                            requireActivity(),
//                            1,
//                            object : OnCustomButtonClick {
//                                override fun onButtonCallBack(codeType: Int, msg: String?) {
//                                    if (!msg.isNullOrEmpty()) {
//
//                                        showLoading()
//                                        inquiryOrderViewModel.retreatOrder(order.id, msg)
//                                    } else {
//                                        showToast("请输入退诊原因")
//                                    }
//                                }
//                            }).show()


                    }

                    else -> {}
                }
            }

        }
    }

    private fun goToChat(userInfo: UserInfo, patientId: String) {
        if (UserInfoManager.getUserType() == "1") {
            PatientChatActivity.start(
                requireContext(),
                userInfo,
                patientId
            )
        } else {
            PractitionerToPatientChatActivity.start(
                requireContext(),
                userInfo,
                patientId
            )
        }
    }

    private fun callPhone(id: String, mainNumber: String?, assistantNumber: String?) {
        ChoosePhoneDialog.Builder(requireActivity(), mainNumber, assistantNumber)
            .setOnNumberChooseCall { s, i ->

                CommonMessageDialog.Builder(requireActivity())
                    .setTitle(getStringFromResource(com.compass.framework.R.string.dialog_tips_title))
                    .setMessage("是否立即呼叫患者？确定后平台会立即呼叫患者，患者接通后会再次呼叫您，请您留意接听电话（电话为029开头）。")
                    .setConfirm(getStringFromResource(com.compass.framework.R.string.default_confirm))

                    .setCancel(getString(com.compass.framework.R.string.default_cancel))
                    .setonCancelListener {
                        it?.dismiss()
                    }
                    .setonConfirmListener {
                        inquiryOrderViewModel.consultationCall(id, s, i)
                        it?.dismiss()
                    }.create().show()

            }.show()


    }

    /**
     * 首页菜单点击事件
     */
    private fun onMenuClick(id: Int) {
        when (id) {
            1 -> {

                //增值服务
                VAServiceActivity.start(requireContext())
            }

            2 -> {
                //随访中心
                FollowUpActivity.start(requireContext())
            }

            3 -> {
                //知识中心
                KnowledgeCenterActivity.start(requireContext())
            }

            4 -> {
//                if (UserInfoManager.isExamine()) {
//                    //会诊中心
//                    ConsultationCenterActivity.start(requireContext())
//                } else {
//                    showToast("您的资料还在审核中")
//                }
                ConsultationCenterActivity.start(requireContext())
            }

            5 -> {
                //团队医生
                TeamDoctorActivity.start(requireContext())
            }

            6 -> {
                //常用工具
//                WebDetailActivity.start(requireContext(), TOOLS_URl, "常用工具")
                havePermission("1851827536909000111","")


            }

        }

    }

    /**
     * 判断是否有权限
     */
    private fun havePermission(account: String, orderId: String) {
        //判断是否有权限
        if (XXPermissions.isGranted(
                requireContext(),
                Permission.RECORD_AUDIO,
                Permission.CAMERA
            )
        ) {
            requestPermission(account, orderId)
        } else {
            CommonMessageDialog.Builder(requireActivity())
                .setTitle(getStringFromResource(com.compass.doctor.R.string.permission_explain))
                .setMessage(getStringFromResource(com.compass.doctor.R.string.video_permission_logs))
                .setConfirm(getStringFromResource(com.compass.framework.R.string.default_confirm))
                .setCancel(getString(com.compass.framework.R.string.default_cancel))
                .setonCancelListener {
                    it?.dismiss()
                }
                .setonConfirmListener {
                    requestPermission(account, orderId)
                    it?.dismiss()
                }.create().show()
        }
    }

    /**
     * 请求权限
     */
    private fun requestPermission(account: String, orderId: String) {
        XXPermissions.with(this)
            //小米应用市场不允许提前获取相册拍照权限，这里先获取存储权限，进入到相册选择页面点击拍照按钮时在获取拍照权限
            .permission(Permission.RECORD_AUDIO)
            .permission(Permission.CAMERA)
            .unchecked()
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (!allGranted) {
                        TipsToast.showTips(R.string.default_agree_permission)
                        return
                    }
                    VideoCallActivity.start(requireContext(), account, orderId)
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    TipsToast.showTips(R.string.default_agree_permission)
                }
            })
    }

    /**
     * 获取首页信息
     */
    private fun getHomeInfo() {
        mainViewModel.orderTodayCount()
        mainViewModel.getUserInfo()
        getPrescribedList()
    }

    private fun getPrescribedList() {
        inquiryOrderViewModel.getConsultationOrder(count = mPage, pageSize = 10, orderType)
    }


    override fun onRefresh(refreshLayout: RefreshLayout) {
        mPage = 1
        getHomeInfo()
        //首页刷新业务
        refreshLayout.finishRefresh()
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        mPage++
        getPrescribedList()
    }
}